/**
 * DeviceInfoPlus - 设备信息增强插件
 * 提供详细的设备参数、网络状态、传感器数据等功能
 */

class DeviceInfoPlus {
    constructor() {
        this._deviceInfo = null;
        this._networkInfo = null;
        this._batteryInfo = null;
        this._sensorData = null;
        this._isEmulator = false;
        this._deviceId = null;
    }

    /**
     * 初始化插件
     * @returns {Promise<void>}
     */
    async init() {
        try {
            // 获取基础设备信息
            this._deviceInfo = await this._getDeviceInfo();
            // 获取网络状态
            this._networkInfo = await this._getNetworkInfo();
            // 获取电池信息
            this._batteryInfo = await this._getBatteryInfo();
            // 检测是否为模拟器
            this._isEmulator = await this._checkEmulator();
            // 生成或获取设备唯一ID
            this._deviceId = await this._generateDeviceId();
            // 初始化传感器监听
            await this._initSensors();
        } catch (error) {
            console.error('DeviceInfoPlus初始化失败:', error);
            throw error;
        }
    }

    /**
     * 获取设备详细信息
     * @returns {Promise<Object>}
     */
    async _getDeviceInfo() {
        return new Promise((resolve) => {
            uni.getSystemInfo({
                success: (res) => {
                    resolve({
                        brand: res.brand,
                        model: res.model,
                        system: res.system,
                        platform: res.platform,
                        screenWidth: res.screenWidth,
                        screenHeight: res.screenHeight,
                        windowWidth: res.windowWidth,
                        windowHeight: res.windowHeight,
                        statusBarHeight: res.statusBarHeight,
                        pixelRatio: res.pixelRatio,
                        language: res.language,
                        version: res.version,
                        SDKVersion: res.SDKVersion,
                        memory: res.memory,
                        storage: res.storage
                    });
                },
                fail: (err) => {
                    console.error('获取设备信息失败:', err);
                    resolve({});
                }
            });
        });
    }

    /**
     * 获取网络状态
     * @returns {Promise<Object>}
     */
    async _getNetworkInfo() {
        return new Promise((resolve) => {
            uni.getNetworkType({
                success: (res) => {
                    resolve({
                        networkType: res.networkType,
                        isConnected: res.networkType !== 'none'
                    });
                },
                fail: (err) => {
                    console.error('获取网络状态失败:', err);
                    resolve({ networkType: 'unknown', isConnected: false });
                }
            });
        });
    }

    /**
     * 获取电池信息
     * @returns {Promise<Object>}
     */
    async _getBatteryInfo() {
        return new Promise((resolve) => {
            // #ifdef APP-PLUS
            plus.navigator.getBatteryInfo({
                success: (res) => {
                    resolve({
                        level: res.level,
                        isCharging: res.isCharging
                    });
                },
                fail: () => {
                    resolve({ level: -1, isCharging: false });
                }
            });
            // #endif

            // #ifdef H5
            if (navigator.getBattery) {
                navigator.getBattery().then(battery => {
                    resolve({
                        level: battery.level * 100,
                        isCharging: battery.charging
                    });
                }).catch(() => {
                    resolve({ level: -1, isCharging: false });
                });
            } else {
                resolve({ level: -1, isCharging: false });
            }
            // #endif
        });
    }

    /**
     * 检测是否为模拟器环境
     * @returns {Promise<boolean>}
     */
    async _checkEmulator() {
        return new Promise((resolve) => {
            // #ifdef APP-PLUS
            const systemInfo = uni.getSystemInfoSync();
            const isEmulator = systemInfo.platform === 'android' && 
                (systemInfo.model.includes('sdk') || 
                 systemInfo.model.includes('emulator') ||
                 systemInfo.model.includes('generic'));
            resolve(isEmulator);
            // #endif

            // #ifdef H5
            resolve(false);
            // #endif
        });
    }

    /**
     * 生成设备唯一ID
     * @returns {Promise<string>}
     */
    async _generateDeviceId() {
        return new Promise((resolve) => {
            // #ifdef APP-PLUS
            plus.device.getInfo({
                success: (deviceInfo) => {
                    const id = this._generateHash(deviceInfo.uuid || deviceInfo.imei || Date.now().toString());
                    resolve(id);
                },
                fail: () => {
                    resolve(this._generateHash(Date.now().toString()));
                }
            });
            // #endif

            // #ifdef H5
            const browserInfo = navigator.userAgent + navigator.language + screen.colorDepth;
            resolve(this._generateHash(browserInfo));
            // #endif
        });
    }

    /**
     * 初始化传感器监听
     * @returns {Promise<void>}
     */
    async _initSensors() {
        // #ifdef APP-PLUS
        this._sensorData = {
            accelerometer: null,
            gyroscope: null,
            compass: null
        };

        // 加速度传感器
        plus.accelerometer.watchAcceleration(
            (res) => {
                this._sensorData.accelerometer = {
                    x: res.xAxis,
                    y: res.yAxis,
                    z: res.zAxis
                };
            },
            (error) => {
                console.error('加速度传感器监听失败:', error);
            },
            { frequency: 1000 }
        );

        // 陀螺仪传感器
        plus.gyroscope.watchGyroscope(
            (res) => {
                this._sensorData.gyroscope = {
                    x: res.xAxis,
                    y: res.yAxis,
                    z: res.zAxis
                };
            },
            (error) => {
                console.error('陀螺仪传感器监听失败:', error);
            },
            { frequency: 1000 }
        );

        // 指南针传感器
        plus.compass.watchHeading(
            (res) => {
                this._sensorData.compass = {
                    heading: res.magneticHeading,
                    accuracy: res.accuracy
                };
            },
            (error) => {
                console.error('指南针传感器监听失败:', error);
            },
            { frequency: 1000 }
        );
        // #endif
    }

    /**
     * 生成简单的哈希值
     * @param {string} str 
     * @returns {string}
     */
    _generateHash(str) {
        let hash = 0;
        for (let i = 0; i < str.length; i++) {
            const char = str.charCodeAt(i);
            hash = ((hash << 5) - hash) + char;
            hash = hash & hash;
        }
        return Math.abs(hash).toString(16);
    }

    /**
     * 获取所有设备信息
     * @returns {Object}
     */
    getAllInfo() {
        return {
            deviceInfo: this._deviceInfo,
            networkInfo: this._networkInfo,
            batteryInfo: this._batteryInfo,
            sensorData: this._sensorData,
            isEmulator: this._isEmulator,
            deviceId: this._deviceId
        };
    }

    /**
     * 监听网络状态变化
     * @param {Function} callback 
     */
    onNetworkChange(callback) {
        uni.onNetworkStatusChange((res) => {
            callback({
                networkType: res.networkType,
                isConnected: res.isConnected
            });
        });
    }

    /**
     * 监听电池状态变化
     * @param {Function} callback 
     */
    onBatteryChange(callback) {
        // #ifdef APP-PLUS
        plus.navigator.setBatteryChangeListener((res) => {
            callback({
                level: res.level,
                isCharging: res.isCharging
            });
        });
        // #endif

        // #ifdef H5
        if (navigator.getBattery) {
            navigator.getBattery().then(battery => {
                battery.addEventListener('levelchange', () => {
                    callback({
                        level: battery.level * 100,
                        isCharging: battery.charging
                    });
                });
                battery.addEventListener('chargingchange', () => {
                    callback({
                        level: battery.level * 100,
                        isCharging: battery.charging
                    });
                });
            });
        }
        // #endif
    }

    /**
     * 销毁插件，清理资源
     */
    destroy() {
        // #ifdef APP-PLUS
        // 停止传感器监听
        plus.accelerometer.clearWatch();
        plus.gyroscope.clearWatch();
        plus.compass.clearWatch();
        // 停止电池监听
        plus.navigator.clearBatteryChangeListener();
        // #endif

        // 清理网络状态监听
        uni.offNetworkStatusChange();
    }
}

export default new DeviceInfoPlus(); 